package exhi.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.stp.core.entity.IGridRowFactory;
import com.stp.core.entity.XGrid;
import com.stp.core.entity.XGridPage;
import com.stp.core.entity.XGridRow;
import com.stp.core.entity.XMsg;
import com.stp.core.util.Identities;

import exhi.entity.EntpBexhi;
import exhi.manager.EntpBexhiMng;

@Controller
@RequestMapping("/entp")
public class EntpBexhiAct extends BaseAct {

	private static final String PATH_TABLE = "/big-table";
	private static final String PATH_VIEW = "/big-view";
	private static final String PATH_DETAIL = "/big-detail";
	private static final String PATH_SAVE = "/big-save";
	private static final String PATH_DELETE = "/big-delete";

	private static final String PATH_TP = "/tp-detail";
	private static final String PATH_TP_SAVE = "/tp-save";

	// 新展申报
	private static final String PATH_LIST = "/big-list";
	// 历展申报
	private static final String PATH_HISTORY_LIST = "/big-history-list";

	// 明细数据
	@RequestMapping(PATH_TP)
	public void tpDetail(@ModelAttribute("entpBexhi") EntpBexhi entpBexhiInfo,
			ModelMap model) {
		model.addAttribute("info", entpBexhiInfo);
	}

	// 明细数据
	@RequestMapping(PATH_TP_SAVE)
	@ResponseBody
	public String tpSave(@ModelAttribute("entpBexhi") EntpBexhi entpBexhiInfo) {
		entpBexhiMng.save(entpBexhiInfo);
		XMsg msg = new XMsg();
		return toJson(msg);
	}

	// 大型国际展表
	@RequestMapping(PATH_TABLE)
	public void table(
			@RequestParam(value = "code", required = true, defaultValue = "") String code,
			ModelMap model) {
		model.addAttribute("code", code);
		
		// 新展申报
		if (code.equalsIgnoreCase("B")) {
			model.addAttribute("url", PATH_LIST.substring(1) + ".jspx");
		}
		// 历展申报
		if (code.equalsIgnoreCase("D")) {
			model.addAttribute("url", PATH_HISTORY_LIST.substring(1) + ".jspx");
		}
	}

	// 权限json数据
	@RequestMapping(PATH_LIST)
	@ResponseBody
	public String infoList(XGridPage page,
			@RequestParam("cap_code") String capCode,
			@RequestParam("cap_name") String capName)
			throws InstantiationException, IllegalAccessException {

		String sql = "from EntpBexhi info where info.status in ('10','20')  and (info.groupId is null or info.groupId='') and info.year='"
				+ getApplyYr() + "' ";
		sql += sqlModel.getSQLChars("info.zhlx", "=", capCode, false, "and");
		sql += sqlModel
				.getSQLChars("info.zlhmc", "like", capName, false, "and");
		sql += " order by info.createtime desc";
		InfoGridRow row = new EntpBexhiAct.InfoGridRow();
		XGrid grid = entpBexhiMng.getXGrid(sql, row, page.getPageNo(),
				page.getPageSize(), false);
		if (null == grid)
			return "";
		return "{\"xGrid\":" + toJson(grid) + "}";
	}

	// 权限json数据
	@RequestMapping(PATH_HISTORY_LIST)
	@ResponseBody
	public String infoHistoryList(XGridPage page,
			@RequestParam("cap_code") String capCode,
			@RequestParam("cap_name") String capName)
			throws InstantiationException, IllegalAccessException {

		String sql = "from EntpBexhi info where info.status in ('10','20')  and info.year='"
				+ getApplyYr() + "' and info.groupId is not null  and info.groupId<>'' ";
		sql += sqlModel.getSQLChars("info.zhlx", "=", capCode, false, "and");
		sql += sqlModel
				.getSQLChars("info.zlhmc", "like", capName, false, "and");
		sql += " order by info.createtime desc";
		InfoGridRow row = new EntpBexhiAct.InfoGridRow();
		XGrid grid = entpBexhiMng.getXGrid(sql, row, page.getPageNo(),
				page.getPageSize(), false);
		if (null == grid)
			return "";
		return "{\"xGrid\":" + toJson(grid) + "}";
	}

	// 明细数据
	@RequestMapping(PATH_VIEW)
	public void infoView(
			@RequestParam(value = "code", required = true, defaultValue = "") String code,
			@ModelAttribute("entpBexhi") EntpBexhi entpBexhiInfo, ModelMap model) {
		model.addAttribute("code", code);
		model.addAttribute("yr", getApplyYr());
		model.addAttribute("info", entpBexhiInfo);
		showView(entpBexhiInfo,model);
	}
	
	// 明细数据
		@RequestMapping(PATH_DETAIL)
		public void infoDetail(
				@RequestParam(value = "code", required = true, defaultValue = "") String code,
				@ModelAttribute("entpBexhi") EntpBexhi entpBexhiInfo, ModelMap model) {
			model.addAttribute("code", code);
			model.addAttribute("yr", getApplyYr());
			model.addAttribute("info", entpBexhiInfo);
		    showView(entpBexhiInfo,model);
		}
	
	public void showView( EntpBexhi entpBexhiInfo, ModelMap model){
		if (null == entpBexhiInfo.getId()
				|| "".equalsIgnoreCase(entpBexhiInfo.getId())) {
			model.addAttribute("projectId", Identities.uuid());
		} else {
			model.addAttribute("projectId", entpBexhiInfo.getId());
		}
		model.addAttribute("deptName", getDeptName(entpBexhiInfo.getZldd()));
		model.addAttribute("info", entpBexhiInfo);
		String zb = "";
		String qt = "";
		String cb = "";
		String zc = "";
		String xb = "";
		zb = this.getEntpRelaction(entpBexhiInfo.getId(), "ZB");// 主办单位
		qt = this.getEntpRelaction(entpBexhiInfo.getId(), "QT");// 其他单位
		cb = this.getEntpRelaction(entpBexhiInfo.getId(), "CB");// 承办单位
		zc = this.getEntpRelaction(entpBexhiInfo.getId(), "ZC");// 支持单位
		xb = this.getEntpRelaction(entpBexhiInfo.getId(), "XB");// 协办单位
		model.addAttribute("zb", zb);
		model.addAttribute("qt", qt);
		model.addAttribute("cb", cb);
		model.addAttribute("zc", zc);
		model.addAttribute("xb", xb);
	}	
	
	// 数据保存
	@RequestMapping(PATH_SAVE)
	public String saveInfo(HttpServletRequest request,@RequestParam( "code") String code,
			@ModelAttribute("entpBexhi") EntpBexhi entpBexhiInfo, ModelMap model)
			throws IllegalStateException, IOException {
		entpBexhiInfo.setCreatetime(new Date());
		if ("10".equalsIgnoreCase(entpBexhiInfo.getStatus())){
			entpBexhiInfo.setStatus("20");
		}
		entpBexhiMng.save(entpBexhiInfo);
		XMsg msg = new XMsg();
		String entpId = entpBexhiInfo.getId();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 大型国际展--银行存款证明&上年度资产证明（审计）
		if (entpBexhiInfo.getZhlx().equalsIgnoreCase("S")) {
			if (saveUpload(multipartRequest, "attach1")) {
				attachMng.saveFileAttach(entpId, "YHCKZM");// 银行存款证明
			} else {
				msg.setState(false);
				msg.setMsg(attachMng.getErrors());
			}
			if (saveUpload(multipartRequest, "attach2")) {

				attachMng.saveFileAttach(entpId, "SNDZCZM");// 上年度资产证明（审计）
			} else {
				msg.setState(false);
				msg.setMsg(attachMng.getErrors());
			}
			if (saveUpload(multipartRequest, "attach3")) {
				attachMng.saveFileAttach(entpId, "XGBMYJ");// 相关部门意见
			} else {
				msg.setState(false);
				msg.setMsg(attachMng.getErrors());
			}
		}
		if (entpBexhiInfo.getSbxh()==null){
			String sql = "update t_entp_bexhi set sbxh=seq('"
					+ entpBexhiInfo.getYear() + "','apply') where  gid='"
					+ entpBexhiInfo.getId() + "'";
			entpBexhiMng.query(sql);
		}
		msg.setState(true);
		return "redirect:" + PATH_TABLE.substring(1)+".jspx?code="+code;
	}

	@RequestMapping(PATH_DELETE)
	@ResponseBody
	public String infoDelete(@RequestParam(value = "ids", required = true, defaultValue = "") String ids,
			@RequestParam("code") String code) {
		delete("t_entp_book", "bid", ids);
		XMsg msg = new XMsg();
		msg.setState(true);
		return toJson(msg);
	}

	@ModelAttribute("entpBexhi")
	public EntpBexhi getEntpSexhiInfo(
			@RequestParam(value = "infoId", required = true, defaultValue = "") String id) {
		EntpBexhi entpBexhi = entpBexhiMng.get(id);
		if (null == entpBexhi) {
			entpBexhi = new EntpBexhi();
		}
		return entpBexhi;
	}

	class InfoGridRow implements IGridRowFactory {
		public XGridRow builderXRow(Object obj) {
			// TODO Auto-generated method stub
			XGridRow xrow = null;
			String s="";
			if (obj instanceof EntpBexhi) {
				xrow = new XGridRow();
				EntpBexhi info = (EntpBexhi) obj;
				xrow.setId(info.getId());
				List t = new ArrayList();
				t.add("");
				t.add(info.getSysInfo());
				t.add(info.getYear());
				t.add(info.getZlhmc());
				t.add(getDeptName(info.getZldd()));
				/*
				if (null == info.getGroupId()
						|| "".equalsIgnoreCase(info.getGroupId())) {
					s = "<font color='red'>新展</font> | ";
				} else {
					s = "<font color='blue'>历展</font> | ";
				}
				t.add(s);*/
				t.add(getStatus(info.getStatus()));
				if (info.getStatus().equalsIgnoreCase("10")){
					t.add("<a href='big-detail.jspx?infoId=" + info.getId()
						+ "&code=" + (info.getGroupId()==null || info.getGroupId().equalsIgnoreCase("") ? "B":"D")
						+ "'>【编辑】</a> <a href='tp-detail.jspx?infoId="
						+ info.getId() + "'>【台批】</a> ");
				}
				if (info.getStatus().equalsIgnoreCase("20")){
					t.add("<a href='big-view.jspx?infoId=" + info.getId()
						+ "&code=" + (info.getGroupId()==null || info.getGroupId().equalsIgnoreCase("") ? "B":"D")
						+ "'>【查看】</a> <a href='tp-detail.jspx?infoId="
						+ info.getId() + "'>【台批】</a> ");
				}
				xrow.setData(t);
			}
			return xrow;
		}
	}

	@Autowired
	@Qualifier("entpBexhiMng")
	private EntpBexhiMng entpBexhiMng;
}
